package com.dawn.module.hospital.controller.app.order;

import cn.hutool.json.JSONUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.dawn.framework.common.exception.ServerException;
import com.dawn.framework.common.pojo.CommonResult;
import com.dawn.framework.common.util.http.HttpUtils;
import com.dawn.framework.common.util.json.JsonUtils;
import com.dawn.framework.common.util.string.StrUtils;
import com.dawn.framework.web.core.util.RequestUtils;
import com.dawn.module.hospital.config.CDBPayConfig;
import com.dawn.module.hospital.controller.app.order.vo.BillQueryReqVO;
import com.dawn.module.hospital.controller.app.order.vo.OrderQueryReqVO;
import com.dawn.module.hospital.controller.app.order.vo.OrderUnifiedReqVO;
import com.dawn.module.hospital.enums.BHConstants;
import com.dawn.module.hospital.enums.ErrorCodeConstants;
import com.dawn.module.hospital.model.pay.PayOrderCreateResModel;
import com.dawn.module.hospital.service.*;
import com.dawn.module.hospital.service.medicalcopy.MedicalCopyService;
import com.dawn.module.hospital.service.qrcodepay.QrcodePayService;
import com.dawn.module.hospital.util.DateUtils;
import com.dawn.module.hospital.util.SecEncryptUtil;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.annotation.security.PermitAll;
import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;
import java.math.BigDecimal;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * @description:
 * @author: cnsu-cmh
 * @time: 2024/8/8 12:08
 */
@Tag(name = "订单支付 APP - bh")
@RestController
@RequestMapping("/bh/pay")
@Validated
@Slf4j
public class AppOrderPayController extends BHService {

    @Resource
    private StringRedisTemplate stringRedisTemplate;

    @Resource
    private RegisterService registerService;

    @Resource
    private OutpatientService outpatientService;

    @Autowired
    private ChsOrderService chsOrderService;

    @Autowired
    private TemplateMsgService templateMsgService;

    @Autowired
    private StaticsService staticsService;

    @Autowired
    private CDBPayConfig payConfig;

    @Autowired
    private InHospitalService inHospitalService;

    @Autowired
    private MedicalCopyService medicalCopyService;

    @Resource
    private QrcodePayService qrcodePayService;

    @Autowired
    private EInvoiceService eInvoiceService;

    @Autowired
    private RefundService refundService;

    @PostMapping(value = "/order/mine")
    @Operation(summary = "我的订单")
    @PermitAll
    public CommonResult orderMine(@Valid @RequestBody BillQueryReqVO reqVO){
        JSONObject jsonObject = staticsService.mineBill(reqVO);
        CommonResult result = CommonResult.error(ErrorCodeConstants.BH_ERROR);
        JSONArray payOrderList = jsonObject.getJSONArray("payOrderList");
        if (payOrderList != null){
            result = CommonResult.success(payOrderList);
        }
        return result;
    }

    @PostMapping(value = "/order/query")
    @Operation(summary = "订单信息查询")
    @PermitAll
    public CommonResult orderQuery(@Valid @RequestBody OrderQueryReqVO reqVO){
        CommonResult result = CommonResult.error(ErrorCodeConstants.BH_ERROR);
        String orderNumber = reqVO.getOrderNumber();
        String orderType = "";
        String orderName = "";
        if(orderNumber.indexOf("GH") != -1) {
            result = registerService.queryByOrderNumber(reqVO.getOrderNumber());
            orderType = BHConstants.ORDER_TYPE_REG;
            orderName = "预约挂号";
        } else if (orderNumber.indexOf("JF") != -1 || orderNumber.indexOf("NAT") != -1 || orderNumber.indexOf("QR") != -1 || orderNumber.indexOf("HIV") != -1) {
            result = outpatientService.queryByOrderNumber(reqVO.getOrderNumber());
            orderType = BHConstants.ORDER_TYPE_RECIPE;
            orderName = "门诊缴费";
        } else if (orderNumber.indexOf("ZYYJ") != -1) {
            result = inHospitalService.queryByOrderNumber(reqVO.getOrderNumber());
            orderType = BHConstants.ORDER_TYPE_PRE_PAYMENT;
            orderName = "住院预交";
        } else if (orderNumber.indexOf("BA") != -1) {
            result = medicalCopyService.queryByApplyNo(reqVO.getOrderNumber());
            orderType = BHConstants.ORDER_TYPE_MEDICAL_COPY;
            orderName = "病案复印";
        }
        if(result.isSuccess()){
            Map map = (Map) result.getData();
            map.put("orderType",orderType);
            map.put("orderName",orderName);

            if(orderType.equals(BHConstants.ORDER_TYPE_RECIPE) && "DETAIL".equals(reqVO.getQueryType())){
                CommonResult payResult = CDBPayUtils.instance().build(CDBPayUtils.WX_CHS).chsQuery(orderNumber);
                log.info("-------订单查询 payQueryResult-----json:"+ JsonUtils.toJsonString(payResult));
                if(payResult.isSuccess()) {
                    JSONObject res = (JSONObject)payResult.getData();
                    JSONObject payOrder = res.getJSONObject("payOrder");
                    JSONObject chsOrder = res.getJSONObject("chsOrder");
                    map.put("payOrder",payOrder);
                    map.put("chsOrder",chsOrder);
                }
            }

            if("DETAIL".equals(reqVO.getQueryType())){
                // 查询电子发票开票信息
                try{
                    CommonResult eReceiptResult = eInvoiceService.query(orderNumber);
                    log.info(orderNumber + "查询电子发票开票信息" + orderNumber + JsonUtils.toJsonString(eReceiptResult));
                    if(eReceiptResult.isSuccess()){
                        map.put("eInvoice", eReceiptResult.getData());
                    }
                }catch (Exception e) {
                    e.printStackTrace();
                    log.warn("查询电子发票开票信息异常" + orderNumber);
                }
            }

            return CommonResult.success(map);
        }
        return result;
    }

    @PostMapping(value = "/order/status")
    @Operation(summary = "订单状态查询")
    @PermitAll
    public CommonResult orderStatus(@Valid @RequestBody OrderQueryReqVO reqVO){
        CommonResult result = CommonResult.error(ErrorCodeConstants.BH_ERROR);
        String orderNumber = reqVO.getOrderNumber();
        String orderType = "";
        String orderName = "";
        if(orderNumber.indexOf("GH") != -1) {
            result = registerService.queryByOrderNumber(reqVO.getOrderNumber());
            orderType = BHConstants.ORDER_TYPE_REG;
            orderName = "预约挂号";
        } else if (orderNumber.indexOf("JF") != -1 || orderNumber.indexOf("NAT") != -1 || orderNumber.indexOf("QR") != -1 || orderNumber.indexOf("HIV") != -1) {
            result = outpatientService.queryBillByOrderNumber(reqVO.getOrderNumber());
            orderType = BHConstants.ORDER_TYPE_RECIPE;
            orderName = "门诊缴费";
        } else if (orderNumber.indexOf("ZYYJ") != -1) {
            result = inHospitalService.queryByOrderNumber(reqVO.getOrderNumber());
            orderType = BHConstants.ORDER_TYPE_PRE_PAYMENT;
            orderName = "住院预交";
        } else if (orderNumber.indexOf("BA") != -1) {
            result = medicalCopyService.queryByApplyNo(reqVO.getOrderNumber());
            orderType = BHConstants.ORDER_TYPE_MEDICAL_COPY;
            orderName = "病案复印";
        }
        if(result.isSuccess()){
            Map map = (Map) result.getData();
            map.put("orderType",orderType);
            map.put("orderName",orderName);
            return CommonResult.success(map);
        }
        return result;
    }

    @PostMapping(value = "/paySignData")
    @Operation(summary = "获取支付下单数据")
    public CommonResult paySignData(@Valid @RequestBody OrderQueryReqVO reqVO) {
        CommonResult result = CommonResult.error(ErrorCodeConstants.BH_ERROR);
        String orderNumber = reqVO.getOrderNumber();
        String orderType = "";
        String orderName = "";
        if(orderNumber.indexOf("GH") != -1) {
            result = registerService.buildPaySignData(reqVO.getOrderNumber());
            orderType = BHConstants.ORDER_TYPE_REG;
            orderName = "预约挂号";
        } else if (orderNumber.indexOf("JF") != -1 || orderNumber.indexOf("NAT") != -1 || orderNumber.indexOf("QR") != -1 || orderNumber.indexOf("HIV") != -1) {
            result = outpatientService.buildPaySignData(reqVO.getOrderNumber());
            orderType = BHConstants.ORDER_TYPE_RECIPE;
            orderName = "门诊缴费";
        } else if (orderNumber.indexOf("ZYYJ") != -1) {
            result = inHospitalService.buildPaySignData(reqVO.getOrderNumber());
            orderType = BHConstants.ORDER_TYPE_PRE_PAYMENT;
            orderName = "住院预交";
        } else if (orderNumber.indexOf("BA") != -1) {
            result = medicalCopyService.buildPaySignData(reqVO.getOrderNumber());
            orderType = BHConstants.ORDER_TYPE_MEDICAL_COPY;
            orderName = "病案复印";
        }
        if(result.isSuccess()){
            Map map = (Map) result.getData();
            map.put("orderType",orderType);
            map.put("orderName",orderName);
            return CommonResult.success(map);
        }
        return result;
    }

    @PostMapping(value = "/paySignMap")
    @Operation(summary = "支付下单")
    public CommonResult pay(@Valid @RequestBody OrderUnifiedReqVO reqVO){
        // 微信公众号
        if (BHConstants.WEIXIN_SERVICE_ACCOUNTS.getCode().equals(reqVO.getAppType())) {
            String orderNumber = reqVO.getOrderNumber();

            String signDataStr = reqVO.getSignDataStr();
            String signDataJsonStr = null;
            try {
                signDataJsonStr = SecEncryptUtil.decryption(signDataStr);
            } catch (Exception e) {
                throw new ServerException(ErrorCodeConstants.BH_ERROR.getCode(),e.getMessage());
            }
            JSONObject signData = JSONObject.parseObject(signDataJsonStr);

            String orderName = signData.getString("orderName");

            if("病案复印".equals(orderName)){
                orderNumber = signData.getString("orderNumber");
            }

            Object orderObj = stringRedisTemplate.opsForValue().get("PayOrderDetails_" + orderNumber);
            if(orderObj != null) {
                String cacheOrderData = orderObj.toString();
                if (!StringUtils.isEmpty(cacheOrderData)) {
                    JSONObject prePayInfo = JSON.parseObject(cacheOrderData);
                    return CommonResult.success(prePayInfo);
                }
            }

            String patientId = signData.getString("patientId");
            String patientName = signData.getString("patientName");
            String clinicNo = signData.getString("clinicNo");
            String cardNo = signData.getString("cardNo");
            String registerNo = signData.getString("registerNo");
            String openid = signData.getString("openid");
            String totalCost = signData.getString("totalCost");

            BigDecimal totalCostB = new BigDecimal(totalCost);
            String body = CDBPayUtils.packageBody(patientId,patientName,
                    StrUtils.getStringValue(clinicNo),
                    StrUtils.getStringValue(cardNo),
                    StrUtils.getStringValue(registerNo));

            String payWay = CDBPayUtils.WX;
            if("病案复印".equals(orderName)){
                payWay = CDBPayUtils.DAWN_PAY;
            }

            String orderTitle = BHConstants.WEIXIN_SERVICE_ACCOUNTS.getMsg()  + "-" + orderName;

            if (orderNumber.indexOf("QR") != -1) {
                orderTitle = BHConstants.PRESCRIPTIONS_QR_CODE.getMsg()  + "-" + orderName;
            }

            CommonResult payResult = CDBPayUtils.instance().build(payWay)
                    .wxJsapiPay(orderNumber,orderTitle,totalCostB.setScale(2, BigDecimal.ROUND_HALF_UP).toString(),
                            body, openid);
            if(payResult.isError()) {
                return payResult;
            }
            JSONObject resData = (JSONObject)payResult.getData();
            PayOrderCreateResModel res = JSONObject.toJavaObject(resData,PayOrderCreateResModel.class);
            String payDataStr = res.getPayData();
            stringRedisTemplate.opsForValue().set("PayOrderDetails_"+orderNumber,payDataStr,30L, TimeUnit.MINUTES);
            JSONObject prePayInfo = JSON.parseObject(payDataStr);
            return CommonResult.success(prePayInfo);
        }

        // 支付宝小程序
        if (BHConstants.ALIPAY_MINI_APPLET.getCode().equals(reqVO.getAppType())) {

        }

        return CommonResult.error(ErrorCodeConstants.BH_ERROR.getCode(),"应用类型不正确");
    }

    @RequestMapping(value = "/notify")
    @Operation(summary = "支付成功通知")
    @PermitAll
    public CommonResult payNotify(HttpServletRequest request) {
        log.info("---------pay notify 支付结果通知参数 start-------");
        JSONObject params = RequestUtils.getReqParamJSON(request);
        log.info("---------pay notify 支付结果通知参数-------params:"+ JSONUtil.toJsonStr(params));

        String mchNo = params.getString("mchNo");
        String appId = params.getString("appId");
        String payOrderId = params.getString("payOrderId");
        String mchOrderNo = params.getString("mchOrderNo");
        String channelOrderNo = params.getString("channelOrderNo");
        Long amountL = params.getLong("amount");

        int state = params.getIntValue("state");
        if(state == 2) {
            boolean isDawnPay = (appId.equals(payConfig.getDawnPay().getAppid()) && mchNo.equals(payConfig.getDawnPay().getMchNo()));
            if (isDawnPay || mchOrderNo.indexOf("QAC") != -1) {
                //保存通知信息、订单号唯一约束，防止重复通知
                Map<String,Object> notifyMap = new HashMap<>();
                notifyMap.put("orderNo",mchOrderNo);
                notifyMap.put("thirdOrderNo",payOrderId);
                notifyMap.put("bizContent",JSONUtil.toJsonStr(params));
                CommonResult addNotifyResult = HttpUtils.postForm(getHisServerUri() + BHConstants.HIS_ADD_ORDER_NOTIFY.getValue(), notifyMap);
                if(addNotifyResult.isError()) {
                    return CommonResult.success("SUCCESS");
                }
                Map<String, Object> paramMap = new HashMap<>();
                paramMap.put("orderNumber", mchOrderNo);
                paramMap.put("payOrderId", payOrderId);
                paramMap.put("thirdOrderNo", channelOrderNo);

                if (mchOrderNo.indexOf("BA") != -1) {
                    CommonResult notifyResult = medicalCopyService.payNotify(paramMap);
                    log.info("---------notify DawnPay BA-------notifyResult.isSuccess:" + notifyResult.isSuccess() + ",message" + notifyResult.getMsg());
                } else if (mchOrderNo.indexOf("QP") != -1 || mchOrderNo.indexOf("QAC") != -1) {
                    CommonResult notifyResult = qrcodePayService.payNotify(paramMap);
                    log.info("---------notify DawnPay QP-------notifyResult.isSuccess:" + notifyResult.isSuccess() + ",message" + notifyResult.getMsg());
                }

                return CommonResult.success("SUCCESS");
            }
            boolean isWxPay = (appId.equals(payConfig.getWx().getAppid()) && mchNo.equals(payConfig.getWx().getMchNo()));
            boolean isAliPay = isWxPay ? false : (appId.equals(payConfig.getAli().getAppid()) && mchNo.equals(payConfig.getAli().getMchNo()));
            if(isWxPay || isAliPay) {
                //保存通知信息、订单号唯一约束，防止重复通知
                Map<String,Object> notifyMap = new HashMap<>();
                notifyMap.put("orderNo",mchOrderNo);
                notifyMap.put("thirdOrderNo",payOrderId);
                notifyMap.put("bizContent",JSONUtil.toJsonStr(params));
                CommonResult addNotifyResult = HttpUtils.postForm(getHisServerUri() + BHConstants.HIS_ADD_ORDER_NOTIFY.getValue(), notifyMap);
                if(addNotifyResult.isError()) {
                    return CommonResult.success("SUCCESS");
                }

                //获取本地订单数据
                BigDecimal yuan = new BigDecimal(amountL).divide(new BigDecimal(100));
                String amount = yuan.setScale(2, BigDecimal.ROUND_HALF_UP).toString();
                Map<String, Object> paramMap = new HashMap<>();
                paramMap.put("orderNumber", mchOrderNo);
                paramMap.put("totalCost", amount);
                paramMap.put("thirdOrderNo", payOrderId);
                paramMap.put("payInfo", JSONUtil.toJsonStr(params));

                String orderType = "";
                if (mchOrderNo.indexOf("GH") != -1) {
                    CommonResult findResult = registerService.queryByOrderNumber(mchOrderNo);
                    if(findResult.isSuccess()) {
                        JSONObject orderObj = (JSONObject)findResult.getData();

                        // 自助机直接返回
                        String payScene = orderObj.getString("payScene");
                        if(payScene.equals(BHConstants.SELF_SERVICE_TERMINAL.getMsg())) {
                            return CommonResult.success("SUCCESS");
                        }

                        String payStatus = orderObj.getString("payStatus");
                        if ("unpaid".equals(payStatus)) {
                            paramMap.put("patientId", orderObj.get("pid"));
                            paramMap.put("openid", orderObj.get("userId"));
                            orderType = BHConstants.ORDER_TYPE_REG;
                        } else {
                            return CommonResult.success("SUCCESS");
                        }
                    }
                } else if (mchOrderNo.indexOf("JF") != -1 || mchOrderNo.indexOf("QR") != -1
                        || mchOrderNo.indexOf("NAT") != -1 || mchOrderNo.indexOf("HIV") != -1 ) {
                    CommonResult findResult = outpatientService.queryBillByOrderNumber(mchOrderNo);
                    if(findResult.isSuccess()) {
                        JSONObject orderObj = (JSONObject)findResult.getData();

                        // 自助机直接返回
                        String payScene = orderObj.getString("payScene");
                        if(payScene.equals(BHConstants.SELF_SERVICE_TERMINAL.getMsg())) {
                            return CommonResult.success("SUCCESS");
                        }

                        String payStatus = orderObj.getString("payStatus");
                        if ("unpaid".equals(payStatus)) {
                            paramMap.put("patientName", orderObj.get("patientName"));
                            paramMap.put("patientId", orderObj.get("pid"));
                            paramMap.put("openid", orderObj.get("userId"));

                            if(mchOrderNo.indexOf("QR") != -1) {
//                                orderType = BHConstants.ORDER_TYPE_RECIPE_QR;
                                orderType = BHConstants.ORDER_TYPE_RECIPE;
                            } else {
                                orderType = BHConstants.ORDER_TYPE_RECIPE;
                            }
                        } else {
                            return CommonResult.success("SUCCESS");
                        }
                    }
                } else if (mchOrderNo.indexOf("ZYYJ") != -1) {
                    CommonResult findResult = inHospitalService.queryByOrderNumber(mchOrderNo);
                    if(findResult.isSuccess()) {
                        JSONObject orderObj = (JSONObject)findResult.getData();

                        // 自助机直接返回
                        String payScene = orderObj.getString("payScene");
                        if(payScene.equals(BHConstants.SELF_SERVICE_TERMINAL.getMsg())) {
                            return CommonResult.success("SUCCESS");
                        }

                        String payStatus = orderObj.getString("payStatus");
                        if ("unpaid".equals(payStatus)) {
                            paramMap.put("patientId", orderObj.get("pid"));
                            paramMap.put("inPatientNo",orderObj.get("inPatientId"));
                            paramMap.put("openid", orderObj.get("userId"));
                            orderType = BHConstants.ORDER_TYPE_REG;
                        } else {
                            return CommonResult.success("SUCCESS");
                        }
                    }
                } else if (mchOrderNo.indexOf("QAC") != -1) {
                    //扫码盒子订单直接返回
                    return CommonResult.success("SUCCESS");
                } else if (mchOrderNo.indexOf("FK") != -1) {
                    // 发卡直接返回
                    return CommonResult.success("SUCCESS");
                }

                CommonResult notifyResult = null;
                if (BHConstants.ORDER_TYPE_REG.equals(orderType)) {
                    notifyResult = registerService.payNotify(paramMap);
                    log.info("---------notify REG-------notifyResult.isSuccess:" + notifyResult.isSuccess() + ",message" + notifyResult.getMsg());
                }

                if (BHConstants.ORDER_TYPE_RECIPE.equals(orderType)) {
                    notifyResult = outpatientService.payNotify(paramMap);
                    log.info("---------notify RECIPE-------notifyResult.isSuccess:" + notifyResult.isSuccess() + ",message" + notifyResult.getMsg());
                }

                if (BHConstants.ORDER_TYPE_PRE_PAYMENT.equals(orderType)) {
                    // TODO 住院预交
                    notifyResult = inHospitalService.payNotify(paramMap);
                    log.info("---------notify PRE_PAYMENT-------notifyResult.isSuccess:" + notifyResult.isSuccess() + ",message" + notifyResult.getMsg());
                }

                if (BHConstants.ORDER_TYPE_RECIPE_QR.equals(orderType)) {
                    // TODO 处方单扫码付
                }

                if (notifyResult != null) {

                } else {

                }
                log.info("---------pay notify 支付结果通知参数 end-------");
                return CommonResult.success("SUCCESS");
            }
            log.info("---------pay notify 支付结果通知参数 end-------");
            return CommonResult.error(ErrorCodeConstants.BH_ERROR);
        }
        return CommonResult.error(ErrorCodeConstants.BH_ERROR);
    }

    @RequestMapping(value = "/chs/notify")
    @Operation(summary = "医保支付成功通知")
    @PermitAll
    public CommonResult chsPayNotify(HttpServletRequest request) {
        log.info("---------chs notify 医保支付结果通知 start-------");
        JSONObject params = RequestUtils.getReqParamJSON(request);
        log.warn("---------医保移动支付 notify 支付结果通知参数-------map:"+ JsonUtils.toJsonString(params));

        String mchNo = params.getString("mchNo");
        String appId = params.getString("appId");
        String payOrderId = params.getString("payOrderId");
        String mchOrderNo = params.getString("mchOrderNo");
        Long amountL = params.getLong("amount");
        int state = params.getIntValue("state");
        if(state == 2) {
            boolean isWxChsPay = (appId.equals(payConfig.getWxChs().getAppid()) && mchNo.equals(payConfig.getWxChs().getMchNo()));
            if(isWxChsPay) {
                //保存通知信息、订单号唯一约束，防止重复通知
                JSONObject notifyMap = new JSONObject();
                notifyMap.put("orderNo",mchOrderNo);
                notifyMap.put("thirdOrderNo",payOrderId);
                notifyMap.put("bizContent",JsonUtils.toJsonString(params));
                CommonResult addNotifyResult = HttpUtils.postForm(getHisServerUri() + BHConstants.HIS_ADD_ORDER_NOTIFY.getValue(), notifyMap);
                if(addNotifyResult.isError()) {
                    return CommonResult.success("SUCCESS");
                }

                BigDecimal yuan = new BigDecimal(amountL).divide(new BigDecimal(100));
                String amount = yuan.setScale(2, BigDecimal.ROUND_HALF_UP).toString();
                Map<String, Object> paramMap = new HashMap<>();
                paramMap.put("orderNumber",mchOrderNo);
                paramMap.put("totalCost",amount);
                paramMap.put("thirdOrderNo",payOrderId);
                paramMap.put("payInfo",JsonUtils.toJsonString(params));

                String payScene = "";
                String orderType = "";

                Map findResultMap = null;
                if (mchOrderNo.indexOf("GH") != -1) {
                    CommonResult findResult = registerService.queryByOrderNumber(mchOrderNo);
                    //挂号
                    if(findResult.isSuccess()) {
                        findResultMap = (Map) findResult.getData();
                        String payStatus = (String)findResultMap.get("payStatus");
                        if("unpaid".equals(payStatus)) {
                            orderType = BHConstants.ORDER_TYPE_REG;
                        } else {
                            return CommonResult.success("SUCCESS");
                        }
                    }
                } else if (mchOrderNo.indexOf("JF") != -1 || mchOrderNo.indexOf("NAT") != -1 || mchOrderNo.indexOf("QR") != -1) {
                    // 缴费
                    CommonResult findResult = outpatientService.queryBillByOrderNumber(mchOrderNo);
                    findResultMap = (Map) findResult.getData();
                    String payStatus = (String)findResultMap.get("payStatus");
                    if("unpaid".equals(payStatus)) {
                        if(payScene.equals(BHConstants.PRESCRIPTIONS_QR_CODE) || mchOrderNo.indexOf("QR") != -1) {
                            orderType = BHConstants.ORDER_TYPE_RECIPE_QR;
                        } else {
                            orderType = BHConstants.ORDER_TYPE_RECIPE;
                        }
                    } else {
                        return CommonResult.success("SUCCESS");
                    }
                }

                if (!CollectionUtils.isEmpty(findResultMap)) {

                    CommonResult payResult = CDBPayUtils.instance().build(CDBPayUtils.WX_CHS).chsQuery(mchOrderNo);

                    log.info("-------微信医保移动支付订单查询 payQueryResult-----json:"+JsonUtils.toJsonString(payResult));
                    if(payResult.isSuccess()) {
                        JSONObject res = (JSONObject)payResult.getData();
                        JSONObject payOrder = res.getJSONObject("payOrder");
                        if(((Integer)payOrder.get("state")).intValue() != 2) {
                            return CommonResult.error(ErrorCodeConstants.BH_ERROR);
                        }
                        JSONObject chsOrder = res.getJSONObject("chsOrder");
                        String patientId = String.valueOf(findResultMap.get("patientId"));
                        String patientName = String.valueOf(findResultMap.get("patientName"));
                        String openid = String.valueOf(findResultMap.get("userId"));
                        String pid = null;
                        int sfgh = 0;
                        if (BHConstants.ORDER_TYPE_REG.equals(orderType)) {
                            // 挂号
                            sfgh = 1;
                            if(findResultMap.get("pid") != null) {
                                pid = String.valueOf(findResultMap.get("pid"));
                            }
                        }
                        if (BHConstants.ORDER_TYPE_RECIPE.equals(orderType)) {
                            // 处方缴费
                            sfgh = 0;
                            if(findResultMap.get("pid") != null) {
                                pid = String.valueOf(findResultMap.get("pid"));
                            }
                        }
                        if (BHConstants.ORDER_TYPE_RECIPE_QR.equals(orderType)) {
                            // 处方二维码
                            sfgh = 0;
                        }

                        // HIS账单支付
                        JSONObject rsp = chsOrderService.chsPayHis(patientId,sfgh,amount,mchOrderNo,chsOrder);

                        Map updateArgs = new HashMap();
                        updateArgs.put("hisProvider",BHConstants.HIS_PROVIDER);
                        updateArgs.put("orderNumber",mchOrderNo);
                        updateArgs.put("thirdOrderNo",payOrderId);
                        updateArgs.put("payInfo",JSONUtil.toJsonStr(params));
                        updateArgs.put("payTypeID", BHConstants.PAY_CARD_WX_CHS_CODE);
                        updateArgs.put("payType",BHConstants.PAY_CARD_WX_CHS_CODE);
                        updateArgs.put("payModeName",BHConstants.PAY_CARD_WX_CHS_HIS);
                        updateArgs.put("operateTime", DateUtils.getDateTime());
                        findResultMap.put("payModeName",BHConstants.PAY_CARD_WX_CHS_HIS);
                        if("0".equals(rsp.getString("code"))) {
                            String errMsg = rsp.getString("msg");
                            log.error("HIS账单支付失败：message=【" +errMsg + "】");

                            updateArgs.put("status","FAILS");

                            if(sfgh == 1) {
                                // TODO 更新本地数据库 HIS结算失败状态  挂号
                            } else {
                                HttpUtils.postForm(getHisServerUri() + BHConstants.HIS_CHS_UPDATE_OUTPATIENT.getValue(), updateArgs);
                            }

                            // 推送退费审核模板消息
                            refundService.saveRefundExamine(BHConstants.ORDER_TYPE_RECIPE,findResultMap,errMsg);
                        } else {
                            // TODO 推送微信模板信息
                            templateMsgService.sendMsgOutpatient(findResultMap);
                            // 收费时间
                            String czsj = rsp.getString("CZSJ");
                            // 结账ID
                            String jzid = rsp.getString("JZID");
                            // 开票标志，0：失败，1：成功
                            int kpbz = rsp.getInteger("KPBZ");
//                            // 发票内网地址
//                            String url = rsp.getString("URL");
//                            // 发票外网地址
//                            String neturl = rsp.getString("NETURL");
//                            // 开票人姓名
//                            String fptt = rsp.getString("FPTT");
//                            // 发票号
//                            String fph = rsp.getString("FPH");
//                            // 开票金额
//                            String fpje = rsp.getString("FPJE");
//                            // 开票日期
//                            String kprq = rsp.getString("KPRQ");

                            updateArgs.put("settleId",jzid);
                            updateArgs.put("operateTime",czsj);
                            updateArgs.put("status","SUCCESS");

                            if(sfgh == 1) {
                                // 挂号 TODO
                                // 1. 更新本地数据库 HIS结算信息
                                // 2. 推送相应的模板消息
                            } else {
                                // 更新本地数据库 HIS结算信息
                                CommonResult updateResult = HttpUtils.postForm(getHisServerUri() + BHConstants.HIS_CHS_UPDATE_OUTPATIENT.getValue(), updateArgs);
                                if (updateResult.isSuccess()) {
                                    JSONObject resultData = (JSONObject) updateResult.getData();

                                    // 开据电子票据
                                    try{
                                        CommonResult eReceiptResult = eInvoiceService.open(BHConstants.ORDER_TYPE_RECIPE,resultData);
                                        log.warn(mchOrderNo + "开据电子票据" + mchOrderNo + JsonUtils.toJsonString(eReceiptResult));
                                    } catch (Exception e) {
                                        e.printStackTrace();
                                        log.warn("电子票据开据失败 " + mchOrderNo);
                                    }
                                }
                            }
                        }

                        // 电子健康卡数据上传
                        try{
                            if(!StringUtils.isEmpty(pid)) {
                                //  TODO 电子健康卡数据上传
//                                ReportDataReq reportDataReq = new ReportDataReq();
//                                if(sfgh == 1) {
//                                    if(DateUtils.getTimeYYMMDD().equals(String.valueOf(findResultMap.get("regDate")))) {
//                                        reportDataReq.setScene("0101012");
//                                    } else {
//                                        reportDataReq.setScene("0101011");
//                                    }
//                                    reportDataReq.setDepartment(findResultMap.get("departmentName").toString());
//                                } else {
//                                    reportDataReq.setScene("0101051");
//                                }
//
//                                uploadEhealthData(pid,reportDataReq);
                            }
                        } catch (Exception e) {
                            e.printStackTrace();
                        }

                        return CommonResult.success("SUCCESS");
                    } else {
                        return CommonResult.success("SUCCESS");
                    }

                }

                return CommonResult.error(ErrorCodeConstants.BH_ERROR);
            }

            return CommonResult.error(ErrorCodeConstants.BH_ERROR);
        }
        return CommonResult.error(ErrorCodeConstants.BH_ERROR);
    }

}
